package com.msb.mall.controller;

import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.google.common.collect.Maps;
import com.msb.common.constart.CacheConstant;
import com.msb.mall.entity.bo.*;
import com.msb.mall.feign.CacheClient;
import com.msb.mall.mapper.ClientBalanceMapper;
import com.msb.mall.mapper.ClientSignMapper;
import com.msb.mall.mapper.ClientTemplateMapper;
import com.msb.mall.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;


/**
 * 测试模块
 *
 * @author mf
 * @since 2025-03-08
 */
@RestController
@RequestMapping("api/test/v1")
@Slf4j
public class TestController {
    @Resource
    private IClientBusinessService clientBusinessService;

    @Resource
    private ClientSignMapper clientSignMapper;

    @Resource
    private ClientTemplateMapper clientTemplateMapper;

    @Resource
    private ClientBalanceMapper clientBalanceMapper;

    @Resource
    private IMobileAreaService mobileAreaService;

    @Resource
    private IMobileDirtywordService mobileDirtywordService;

    @Resource
    private IMobileBlackService blackService;

    @Autowired
    private CacheClient cacheClient;

    @Resource
    private IChannelService channelService;

    @Resource
    private IClientChannelService clientChannelService;


    /**
     * 客户信息设置到redis测试
     */
    @GetMapping("findById/{id}")
    public String findById(@PathVariable("id") Long id) {
        final ClientBusiness clientBusiness = clientBusinessService.selectById(id);
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); // 注册 JavaTimeModule

        // 将 ClientBusiness 对象转换为 Map
        final Map<String, Object> map = objectMapper.convertValue(clientBusiness, Map.class);
        log.info("clientBusiness:{}", clientBusiness);
        cacheClient.hmset("client_business:" + clientBusiness.getApikey(), map);
        return "test";
    }

    /**
     * 客户签名设置到redis测试
     */
    @GetMapping("clientSignFindById/{clientId}")
    public String clientSignFindById(@PathVariable("clientId") Long clientId) throws JsonProcessingException {
        // 根据客户id查询数据
        final List<ClientSign> clientSignList = clientSignMapper.findByClientId(clientId);

        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); // 注册 JavaTimeModule
        final List<Map> mapList =
                clientSignList.stream().map(cs -> objectMapper.convertValue(cs, Map.class)).collect(Collectors.toList());

        final Map[] array = mapList.toArray(new Map[]{});
        cacheClient.sadd("client_sign:" + clientId, array);
        return "ok";
    }

    /**
     * 客户模板设置到redis测试
     */
    @GetMapping("clientTemplateBySingId/{singId}")
    public String clientTemplateBySingId(@PathVariable("singId") Long singId) {
        // 根据客户id查询数据
        final List<ClientTemplate> list = clientTemplateMapper.findBySingId(singId);
        if (list.isEmpty()) {
            return "ok";
        }
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule()); // 注册 JavaTimeModule
        final List<Map> mapList =
                list.stream().map(cs -> objectMapper.convertValue(cs, Map.class)).collect(Collectors.toList());

        final Map[] array = mapList.toArray(new Map[]{});
        cacheClient.sadd("client_template:" + singId, array);
        return "ok";
    }

    /**
     * 客户余额redis测试
     */
    @GetMapping("clientBalanceMapperByClientId/{clientId}")
    public String clientBalanceMapperByClientId(@PathVariable("clientId") Long clientId) {
        // 根据客户id查询数据
        final Long balance = clientBalanceMapper.findByClientId(clientId);
        Map<String, Object> longMap = new HashMap<>();
        longMap.put("balance", balance);
        cacheClient.hmset("client_balance:" + clientId, longMap);
        return "ok";
    }


    /**
     * 查询数据库所有归属地到redis
     */
    @GetMapping("mobileArea")
    public void mobileAreaAll() {
        int mobileCount = mobileAreaService.selectCount(null);
        log.info("mobileCount:{}", mobileCount);
        // 把查询出来的数据按照5000一次进行查询并设置到redis中
        int pageSize = 500;
        for (int i = 0; i < mobileCount; i += pageSize) {
            Page<MobileArea> page = new Page<>();
            int count = i / pageSize + 1;
            page.setSize(pageSize).setCurrent(count);
            Page<MobileArea> areaPage = mobileAreaService.selectPage(page, null);
            List<MobileArea> areaList = areaPage.getRecords();
            log.info("总次数:{},已循环次数：{}", mobileCount / pageSize, count);
            Map<String, String> map = Maps.newHashMapWithExpectedSize(areaList.size());
            for (MobileArea mobileArea : areaList) {
                map.put(CacheConstant.PHASE + mobileArea.getMobileNumber(),
                        mobileArea.getMobileArea() + "," + mobileArea.getMobileType());
            }
            cacheClient.pipelineString(map);
        }
    }

    /**
     * 添加敏感词到redis
     */
    @GetMapping("mobileDirtyword")
    public void mobileDirtywordAll() {
        final List<MobileDirtyword> dirtywordList = mobileDirtywordService.selectList(null);
        List<String> listString = new ArrayList<>();
        for (MobileDirtyword mobileDirtyword : dirtywordList) {
            listString.add(mobileDirtyword.getDirtyword());
        }
        cacheClient.sAddString(CacheConstant.DIRTYWORD, listString.toArray(new String[]{}));
    }

    /**
     * 缓存黑名单到redis
     */
    @GetMapping("mobileBlack")
    public void mobileBlackAll() {
        int count = blackService.selectCount(null);
        int pageSize = 500;
        for (int i = 0; i < count; i += pageSize) {
            Page<MobileBlack> blackPage = new Page<>();
            int current = i / pageSize + 1;
            blackPage.setSize(pageSize).setCurrent(current);
            Page<MobileBlack> selectPage = blackService.selectPage(blackPage, null);
            List<MobileBlack> records = selectPage.getRecords();

            HashMap<String, String> hashMap = Maps.newHashMapWithExpectedSize(records.size());
            for (MobileBlack record : records) {
                String blackNumber = record.getBlackNumber();
                String key =
                        (record.getClientId() == 0 ? CacheConstant.GLOBAL_BLACK :
                                CacheConstant.CLIENT_BLACK + record.getClientId()) + blackNumber;
                hashMap.put(key, CacheConstant.DEFAULT_VALUE);
            }
            cacheClient.pipelineString(hashMap);

            log.info("存储黑名单信息到redis" + (current / pageSize) + ":" + current);
        }
    }

    /**
     * 通道信息设置到redis
     */
    @GetMapping("channel")
    public void channel() {
        final List<Channel> channelList = channelService.selectList(null);
        for (Channel channel : channelList) {
            channel.setUpdated(null);
            channel.setCreated(null);
            final ObjectMapper objectMapper = new ObjectMapper();
            final Map map = objectMapper.convertValue(channel, Map.class);

            cacheClient.hmset(CacheConstant.CHANNEL + channel.getId(), map);
        }
    }

    /**
     * 客户通道设置到redis
     */
    @GetMapping("clientChannel")
    public void clientChannel() {
        clientChannelService.selectList(null).forEach(channel -> {
            channel.setUpdated(null);
            channel.setCreated(null);
            final ObjectMapper objectMapper = new ObjectMapper();
            final Map map = objectMapper.convertValue(channel, Map.class);
            cacheClient.sadd(CacheConstant.CLIENT_CHANNEL + channel.getClientId(), map);
        });
    }


}
